﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Collections;

public partial class sale_input : System.Web.UI.Page
{
    protected ArrayList dlist = new ArrayList();
    protected ArrayList ItemList_year = new ArrayList();
    protected ArrayList ItemList_month = new ArrayList();
    protected ArrayList ItemList_day = new ArrayList();
    protected ArrayList ItemList_hour = new ArrayList();
    protected ArrayList ItemList_minute = new ArrayList();
    protected ArrayList ItemList_second = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["USERNAME"] == null)
        {
            Response.Redirect("error_log", true);
        }
        if (!IsPostBack)
        {
            dlist.Add("无优惠活动");
            SqlConnection sc = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
            sc.Open();
            DateTime now = DateTime.Now;
            string start_now = now.Year + "-" + now.Month + "-" + now.Day + " " + now.Hour + ":" + now.Minute + ":" + now.Second;
            string end_now = start_now;
            SqlCommand get_discount = new SqlCommand("select DISCOUNT_TITLE from INFO_DISCOUNT where DISCOUNT_START<convert(smalldatetime,@start) and DISCOUNT_END>convert(smalldatetime,@end) and ENTER_ID=@eid1", sc);
            get_discount.Parameters.AddWithValue("@start", start_now);
            get_discount.Parameters.AddWithValue("@end", end_now);
            get_discount.Parameters.AddWithValue("@eid1", Session["ENTERID"].ToString());
            SqlDataReader r = get_discount.ExecuteReader();
            while (r.Read())
            {
                dlist.Add(r.GetString(r.GetOrdinal("DISCOUNT_TITLE")));
            }
            r.Close();
            sc.Close();
            ItemList_year.Add(2013);
            ItemList_year.Add(2014);

            for (int m = 1; m < 13; m++)
                ItemList_month.Add(m);

            for (int d = 1; d < 32; d++)
                ItemList_day.Add(d);

            for (int h = 0; h < 24; h++)
                ItemList_hour.Add(h);

            for (int mi = 0; mi < 60; mi++)
                ItemList_minute.Add(mi);

            for (int s = 0; s < 60; s++)
                ItemList_second.Add(s);

            DropDownList1.DataBind();
            DropDownList2.DataBind();
            DropDownList4.DataBind();
            DropDownList5.DataBind();
            DropDownList6.DataBind();
            DropDownList7.DataBind();
            dropdownlist3.DataBind();
            DateTime t = DateTime.Now;
            DropDownList1.SelectedValue = t.Year.ToString();
            DropDownList2.SelectedValue = t.Month.ToString();
            DropDownList7.SelectedValue = t.Day.ToString();
            DropDownList4.SelectedValue = t.Hour.ToString();
            DropDownList5.SelectedValue = t.Minute.ToString();
            DropDownList6.SelectedValue = t.Second.ToString();
        }
        /*注：
         * 若有参数传来则指定输入框的内容，若没有传来的参数则跳过此步
         * */
        if (Request.Params["iid"] != null && Request.Params["dname"] != null && Request.Params["iid"].Equals("null") == false && Request.Params["dname"].Equals("null") == false)
        {
            try
            {
                dropdownlist3.SelectedValue = Request.Params["dname"].ToString();
                TextBox4.Text = Request.Params["iid"].ToString();
            }
            finally
            {
            }
        }

    }
    /// <summary>
    /// 判断日期是否合法
    /// </summary>
    /// <param name="year"></param>
    /// <param name="month"></param>
    /// <param name="day"></param>
    /// <param name="hour"></param>
    /// <param name="minute"></param>
    /// <param name="second"></param>
    /// <returns></returns>
    public bool isLegal(int year, int month, int day, int hour, int minute, int second)
    {
        if (year < 0 || year > 9999)
            return false;
        if (month < 0 || month > 12)
            return false;
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
        {
            if (day < 0 || day > 31)
                return false;
        }
        else if (month == 2)
        {
            if (year % 100 == 0 && year % 400 == 0)
            {//100闰年
                if (day < 0 || day > 29)
                    return false;
            }
            else if (year % 100 != 0 && year % 4 == 0)
            {//非整百闰年
                if (day < 0 || day > 29)
                    return false;
            }
            else
            {
                if (day < 0 || day > 28)
                    return false;
            }
        }
        else
        {
            if (day < 0 || day > 31)
                return false;
        }

        return true;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        bool exist = false;
        string input_user = TextBox4.Text;
        string input_pro = TextBox1.Text;
        string indid = "";
        string proid = "";
        string enter_id = "";
        string enter_name = Session["USERNAME"].ToString();
        int year;
        int month;
        int day;
        int hour;
        int minute;
        int second;

        year = Convert.ToInt32(DropDownList1.Text);
        month = Convert.ToInt32(DropDownList2.Text);
        day = Convert.ToInt32(DropDownList7.Text);
        hour = Convert.ToInt32(DropDownList4.Text);
        minute = Convert.ToInt32(DropDownList5.Text);
        second = Convert.ToInt32(DropDownList6.Text);
        if (isLegal(year, month, day, hour, minute, second) == true)
        {
            #region Date_legal
            SqlConnection sc = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
            sc.Open();

            //获取企业用户ID

            enter_id = Session["ENTERID"].ToString();

            // 检查用户名称和产品名称是否分别存在，若存在则check=true
            SqlCommand com_exist = new SqlCommand();
            com_exist.Connection = sc;
            com_exist.CommandText = "select IND_ID from INFO_IND where IND_NAME=@name";
            com_exist.Parameters.AddWithValue("@name", input_user);
            object a = com_exist.ExecuteScalar();
            SqlCommand com_exist1 = new SqlCommand();
            com_exist1.Connection = sc;
            com_exist1.CommandText = "select PRODUCT_ID from INFO_PRODUCT where PRODUCT_NAME=@name";
            com_exist1.Parameters.AddWithValue("@name", input_pro);
            object b = com_exist1.ExecuteScalar();
            if (b != null && a != null)
            {
                exist = true;
                proid = b.ToString();
                indid = a.ToString();
            }


            if (exist == true)
            {
                SqlCommand com_checkd = new SqlCommand();
                com_checkd.Connection = sc;
                com_checkd.CommandText = "select ENTER_ID from INFO_PRODUCT where PRODUCT_ID=@id";
                com_checkd.Parameters.AddWithValue("@id", proid);
                string enter_id1 = com_checkd.ExecuteScalar().ToString();
                if (enter_id.Equals(enter_id1) == true)
                {
                    //将四项信息录入数据库的PRODUCT_SALE表并且给用户加上积分
                    SqlCommand com_credits = new SqlCommand();
                    com_credits.Connection = sc;
                    com_credits.CommandText = "update INFO_IND set IND_CREDITS=IND_CREDITS+(select CREDITS_RATE from INFO_PRODUCT where PRODUCT_ID=@id)*@sum where IND_ID=@idd";
                    com_credits.Parameters.AddWithValue("@id", proid);
                    com_credits.Parameters.AddWithValue("@sum", Convert.ToInt32(TextBox2.Text));
                    com_credits.Parameters.AddWithValue("@idd", indid);
                    while (Application["sqllock"] == "lock")
                    {//检测是否已经锁住               
                        System.Threading.Thread.Sleep(2000);
                    }
                    Application["sqllock"] = "lock";//上锁 
                    try
                    {
                        com_credits.ExecuteNonQuery();
                    }
                    finally
                    {
                        Application["sqllock"] = "unlock";//解锁
                    }

                    //找出直接推荐人并给推荐人账户加上相同积分
                    SqlCommand com_getintro = new SqlCommand();
                    com_getintro.Connection = sc;
                    com_getintro.CommandText = "select INTRO_FROM from IND_CARE where IND_ID=@id and ENTER_ID=@idd";
                    com_getintro.Parameters.AddWithValue("@id", indid);
                    com_getintro.Parameters.AddWithValue("@idd", enter_id);
                    object tmp_a = com_getintro.ExecuteScalar();
                    if (tmp_a != null)//存在就给推荐人账户加上一样的积分
                    {
                        string from_id = tmp_a.ToString();
                        SqlCommand com_credits1 = new SqlCommand();
                        com_credits1.Connection = sc;
                        com_credits1.CommandText = "update INFO_IND set IND_CREDITS=IND_CREDITS+(select CREDITS_RATE from INFO_PRODUCT where PRODUCT_ID=@id)*@sum where IND_ID=@idd";
                        com_credits1.Parameters.AddWithValue("@id", proid);
                        com_credits1.Parameters.AddWithValue("@sum", Convert.ToInt32(TextBox2.Text));
                        com_credits1.Parameters.AddWithValue("@idd", from_id);
                        while (Application["sqllock"] == "lock")
                        {//检测是否已经锁住               
                            System.Threading.Thread.Sleep(2000);
                        }
                        Application["sqllock"] = "lock";//上锁
                        try
                        {
                            com_credits1.ExecuteNonQuery();
                        }
                        finally
                        {
                            Application["sqllock"] = "unlock";//解锁
                        }

                    }
                    string discount = dropdownlist3.Text;
                    if (discount.Equals("无优惠活动") == true)
                    {
                        discount = null;
                    }
                    else
                    {
                        SqlCommand get_did = new SqlCommand("select DISCOUNT_ID from INFO_DISCOUNT where DISCOUNT_TITLE=@dtitle and ENTER_ID=@eid2", sc);
                        get_did.Parameters.AddWithValue("@dtitle", discount);
                        get_did.Parameters.AddWithValue("@eid2", Session["ENTERID"].ToString());
                        discount = get_did.ExecuteScalar().ToString();
                    }

                    SqlCommand com_update = new SqlCommand();
                    com_update.Connection = sc;
                    com_update.CommandText = "insert into PRODUCT_SALE values (@ind,@pro,@sum,@date,@did)";
                    com_update.Parameters.AddWithValue("@ind", indid);
                    com_update.Parameters.AddWithValue("@pro", proid);
                    com_update.Parameters.AddWithValue("@sum", TextBox2.Text);
                    com_update.Parameters.AddWithValue("@date", year + "-" + month + "-" + day + " " + hour + "-" + minute + "-" + second);
                    com_update.Parameters.AddWithValue("@did", discount);
                    while (Application["sqllock"] == "lock")
                    {//检测是否已经锁住               
                        System.Threading.Thread.Sleep(2000);
                    }
                    Application["sqllock"] = "lock";//上锁 

                    try
                    {
                        if (com_update.ExecuteNonQuery() == 1)
                        {
                            Application["sqllock"] = "unlock";//解锁
                            Page.RegisterStartupScript("ss", "<script>alert('成功录入销售记录！')</script>");
                            return;
                        }
                        else
                        {
                            Application["sqllock"] = "unlock";//解锁
                            Page.RegisterStartupScript("ss", "<script>alert('数据库异常，请重试！')</script>");
                            return;
                        }
                    }
                    finally
                    {
                        Application["sqllock"] = "unlock";//解锁
                    }
                    sc.Close();
                }
                else
                {
                    sc.Close();
                    Page.RegisterStartupScript("ss", "<script>alert('该产品不是正在登录平台用户的产品,请确认名称后重新输入！')</script>");
                    return;
                }
            }
            else
            {
                Page.RegisterStartupScript("ss", "<script>alert('输入的用户ID或产品ID不存在,请确认后重新输入！')</script>");
                return;
            }
            #endregion
        }
        else
        {
            Page.RegisterStartupScript("ss", "<script>alert('日期不合法，请检查后确认！')</script>");
            return;
        }
    }

}